package com.gwt.tirso.gymkhana.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.tirso.gymkhana.client.Gymkhana;
import com.gwt.tirso.gymkhana.client.IContestService;
import com.gwt.tirso.gymkhana.client.Question;

@SuppressWarnings("serial")
public class ContestServiceImpl extends RemoteServiceServlet implements IContestService {

	/*private IGymkhanaDAO gdao = new JDBCGymkhanaDAO();
	private IQuestionDAO qdao = new JDBCQuestionDAO();
	private IQuestReferencesDAO qrdao = new JDBCQuestReferencesDAO();*/
	
	@SuppressWarnings("finally")
	@Override
	public Gymkhana extractGymkhana(String name,
			String pass) {
		
		Gymkhana g = null;
		Gymkhana gaux = null;
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		
		try{
			tx.begin();
			
			String query = "select from " + Gymkhana.class.getName() + " where name == '" + name + "' && pass == '" + pass + "'";
			List<Gymkhana> lg = (List<Gymkhana>) pm.newQuery(query).execute();
			g = lg.get(0);
			
			gaux = pm.detachCopy(g);
			
			tx.commit();
			
		}finally{
			if (tx.isActive()) {
                tx.rollback();
            }

			pm.close();
			
			return gaux;	
		}
		
		/*
		//first, i take the Gymkhana with the name and pass. If it doesn´t exist, return null
		Gymkhana g = gdao.selectGymkhanaByNameAndPass(name, pass);
		if(g.getId() == null){
			return null;
		}
		
		//secondly, with the object Gymkhana on my hands,
		//i look for the Questions ids in the reference list
		listIdQ = qrdao.selectGymkhanaQuestions(g);
		if(listIdQ == null){
			return null;
		}
		
		//now, we only need to extract the questions with their own id
		for(String s:listIdQ){
			listQ.add(qdao.selectQuestionById(s));
		}
		
		
		g.setQuestionList(listQ);*/
		
	}

	@Override
	public List<Question> extractQuestionList(Gymkhana g) {
		
		List<Question> lq = null;
		List<Question> lqaux = new ArrayList<Question>();
 	    Gymkhana gaux = null;
 	    	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		
		
		try{
			tx.begin();
			
			gaux  = pm.detachCopy(g);
			
			String query = "select from " + Question.class.getName() + " where gymkId == '" + gaux.getId() +"'";
			lq = (List<Question>) pm.newQuery(query).execute();
			
			for(Question q: lq){
				lqaux.add(q);
			}
						
			tx.commit();
			
		}finally{
			if (tx.isActive()) {
                tx.rollback();
            }

			pm.close();
			
		}
		return lqaux;		
	}	
}
